/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2022-05-26     Administrator       the first version
 */
#include "modbus_interface.h"
#include "mqtt_protocol.h"
#include <stdio.h>
#define DBG_ENABLE
#define DBG_SECTION_NAME    "modbusRTU poll"
#ifdef TCPCLIENT_DEBUG
#define DBG_LEVEL           DBG_LOG
#else
#define DBG_LEVEL           DBG_INFO
#endif /* TCPCLIENT_DEBUG */
#define DBG_COLOR
#include <rtdbg.h>
#define MIN_POLL_TIMESEC 5
char debug_MODBUS = 0;
unsigned char bufferModbus[1024];

static void modbus_poll_entry(void *parameter)
{
    modbus_t *ctx = (modbus_t *) parameter;
    uint16_t tab_reg[64] = {0};
    int len = 0;
    int num = 0;
    while (1)
    {
        memset(tab_reg, 0, 64 * 2);
        int regs = modbus_read_registers(ctx, 0, 20, tab_reg);
        LOG_D("-------------------------------------------\n");
        LOG_D("[%4d][read num = %d]", num, regs);
        num++;
        int i;
        len = 0;
        for (i = 0; i < 20; i++)
        {
            LOG_D("<%#x>", tab_reg[i]);
            len += sprintf(&bufferModbus[len],"<%#x>",tab_reg[i]);
        }
        LOG_D("\n");
        LOG_D("-------------------------------------------\n");
        bufferModbus[len] = 0;
        //rt_kprintf("%s\n",bufferModbus);
        mqtt_interface_send(bufferModbus, len);
        rt_thread_mdelay(1000);
    }
    modbus_close(ctx);

    modbus_free(ctx);
}
rt_bool_t initModbusRTU(void)
{
    modbus_t *ctx = RT_NULL;
    ctx = modbus_new_rtu("/dev/uart5", 115200, 'N', 8, 1);
    if(ctx == RT_NULL){
        LOG_E("Not init modbus ok\n");
        return RT_FALSE;
    }
    modbus_set_error_recovery(ctx, (modbus_error_recovery_mode)(MODBUS_ERROR_RECOVERY_LINK | MODBUS_ERROR_RECOVERY_PROTOCOL));
    modbus_rtu_set_serial_mode(ctx, MODBUS_RTU_RS232);

    modbus_set_slave(ctx, 1);
    modbus_connect(ctx);
    if(debug_MODBUS)
        modbus_set_debug(ctx,1);
    else
        modbus_set_debug(ctx,0);
    modbus_set_response_timeout(ctx, 0, 1000000);

#define MODBUS_LINK_THREAD_TICK           20
#define MODBUS_LINK_THREAD_STACK_SIZE     (1024 + 512)
#define MODBUS_LINK_THREAD_PRIORITY       (RT_THREAD_PRIORITY_MAX - 2)

    rt_thread_t tid;
    char tname[RT_NAME_MAX] = {0};

    rt_snprintf(tname, RT_NAME_MAX, "%s", "modbus_poll");

    /* create ec200x link status polling thread  */
    tid = rt_thread_create(tname, modbus_poll_entry, (void *)ctx,
            MODBUS_LINK_THREAD_STACK_SIZE, MODBUS_LINK_THREAD_PRIORITY, MODBUS_LINK_THREAD_TICK);
    if (tid != RT_NULL)
    {
        rt_thread_startup(tid);
    }

    return RT_TRUE;
}
